import { z } from "zod";
import { icepick } from "@/icepick-client";

interface HolidayResponse {
  date: string;
  localName: string;
  name: string;
  countryCode: string;
  fixed: boolean;
  global: boolean;
  counties: string[] | null;
  launchYear: number | null;
  types: string[];
}

export const holiday = icepick.tool({
  name: "holiday",
  description: "Get the current holiday in a given country",
  inputSchema: z.object({
    country: z.string()
  }),
  outputSchema: z.object({
    country: z.string(),
    holidayName: z.string().optional(),
    holidayDate: z.string().optional(),
    isToday: z.boolean(),
    nextHoliday: z.string().optional(),
    summary: z.string()
  }),
  fn: async (input) => {
    try {
      const currentYear = new Date().getFullYear();
      const today = new Date().toISOString().split('T')[0]; // YYYY-MM-DD format
      
      // Use public holidays API
      const holidayUrl = `https://date.nager.at/api/v3/PublicHolidays/${currentYear}/${encodeURIComponent(input.country)}`;
      const response = await fetch(holidayUrl);
      
      if (!response.ok) {
        throw new Error(`Country '${input.country}' not found or API unavailable`);
      }
      
      const holidays: HolidayResponse[] = await response.json();
      
      // Find today's holiday
      const todayHoliday = holidays.find(holiday => holiday.date === today);
      
      if (todayHoliday) {
        return {
          country: input.country,
          holidayName: todayHoliday.localName || todayHoliday.name,
          holidayDate: todayHoliday.date,
          isToday: true,
          summary: `Today is ${todayHoliday.localName || todayHoliday.name} in ${input.country}`
        };
      }
      
      // Find next upcoming holiday
      const upcomingHoliday = holidays
        .filter(holiday => holiday.date > today)
        .sort((a, b) => a.date.localeCompare(b.date))[0];
      
      if (upcomingHoliday) {
        const holidayDate = new Date(upcomingHoliday.date);
        return {
          country: input.country,
          holidayName: upcomingHoliday.localName || upcomingHoliday.name,
          holidayDate: upcomingHoliday.date,
          isToday: false,
          nextHoliday: `${upcomingHoliday.localName || upcomingHoliday.name} on ${holidayDate.toLocaleDateString()}`,
          summary: `Next holiday in ${input.country}: ${upcomingHoliday.localName || upcomingHoliday.name} on ${holidayDate.toLocaleDateString()}`
        };
      }
      
      return {
        country: input.country,
        isToday: false,
        summary: `No upcoming holidays found for ${input.country} this year`
      };
    } catch (error) {
      return {
        country: input.country,
        isToday: false,
        summary: `Unable to get holiday information for ${input.country}: ${error instanceof Error ? error.message : 'Unknown error'}`
      };
    }
  }
});